package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.common.entity.PageResult;
import com.atguigu.dao.TravelGroupDao;
import com.atguigu.pojo.TravelGroup;
import com.atguigu.service.TravelGroupService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {

    @Autowired
    TravelGroupDao travelGroupDao;
    @Override
    public void groupAndItemAdd(TravelGroup travelGroup, List<Integer> ids) {
        //添加旅游项
        travelGroupDao.groupAdd(travelGroup);
        //添加旅游项和旅游详情的关系
        insertGroupAndItemId(ids,travelGroup.getId());
    }

    @Override
    public TravelGroup selectId(Integer id) {
        TravelGroup travelGroup = travelGroupDao.selectId(id);
        return travelGroup;
    }

    @Override
    public void groupUpdate(TravelGroup travelGroup,List<Integer> ids) {
        //根据id更新旅游项信息 同时更新中间表的对应关系
        travelGroupDao.groupUdate(travelGroup);
        Integer groupId = travelGroup.getId();

        //删除中间表的信息
        travelGroupDao.deleteGroupIdItem(groupId);

        insertGroupAndItemId(ids, groupId);

    }

    private void insertGroupAndItemId(List<Integer> ids, Integer groupId) {
        //重新插入中间表
        for (Integer ItemId : ids) {
            travelGroupDao.groupAndItemAdd(groupId, ItemId);
        }
    }

    @Override
    public PageResult selectPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<TravelGroup> page = travelGroupDao.selectPage(queryString);
        return new PageResult(page.getTotal(),page.getResult(), (long) page.getPages());
    }

    //查找中间表
    @Override
    public List<Integer> findGroupAndItem(Integer id) {
        List<Integer> ids = travelGroupDao.findGroupAndItem(id);
        return ids;
    }

    @Override
    public List<TravelGroup> selectAll() {
        List<TravelGroup> travelGroups = travelGroupDao.selectAll();
        return travelGroups;
    }
}
